<template>
  <div class="form-validation-demo">
    <div class="example-section">
      <h3 class="section-title">基础表单验证</h3>
      <p class="section-description">常见的表单验证规则和错误提示</p>

      <div class="demo-container">
        <div class="demo-wrapper">
          <a-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            layout="vertical"
            class="demo-form"
          >
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="用户名" name="username">
                  <a-input v-model:value="basicForm.username" placeholder="请输入用户名" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="邮箱" name="email">
                  <a-input v-model:value="basicForm.email" placeholder="请输入邮箱" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="密码" name="password">
                  <a-input-password v-model:value="basicForm.password" placeholder="请输入密码" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="确认密码" name="confirmPassword">
                  <a-input-password v-model:value="basicForm.confirmPassword" placeholder="请确认密码" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="手机号" name="phone">
                  <a-input v-model:value="basicForm.phone" placeholder="请输入手机号" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="年龄" name="age">
                  <a-input-number v-model:value="basicForm.age" placeholder="请输入年龄" :min="1" :max="120" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleBasicSubmit">提交</a-button>
                <a-button @click="handleBasicReset">重置</a-button>
                <a-button @click="handleBasicValidate">验证</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <div class="result-display">
          <div class="result-label">表单数据：</div>
          <div class="result-value">
            <pre>{{ JSON.stringify(basicForm, null, 2) }}</pre>
          </div>
        </div>
      </div>
    </div>

    <div class="example-section">
      <h3 class="section-title">自定义验证规则</h3>
      <p class="section-description">自定义验证函数和复杂验证逻辑</p>

      <div class="demo-container">
        <div class="demo-wrapper">
          <a-form
            ref="customFormRef"
            :model="customForm"
            :rules="customRules"
            layout="vertical"
            class="demo-form"
          >
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="身份证号" name="idCard">
                  <a-input v-model:value="customForm.idCard" placeholder="请输入身份证号" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="银行卡号" name="bankCard">
                  <a-input v-model:value="customForm.bankCard" placeholder="请输入银行卡号" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="网站URL" name="website">
                  <a-input v-model:value="customForm.website" placeholder="请输入网站地址" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="IP地址" name="ipAddress">
                  <a-input v-model:value="customForm.ipAddress" placeholder="请输入IP地址" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="密码强度" name="strongPassword">
              <a-input-password v-model:value="customForm.strongPassword" placeholder="请输入强密码" />
              <div class="password-strength">
                <div class="strength-bar">
                  <div
                    class="strength-fill"
                    :class="getPasswordStrengthClass(customForm.strongPassword)"
                    :style="{ width: getPasswordStrengthWidth(customForm.strongPassword) }"
                  ></div>
                </div>
                <span class="strength-text">{{ getPasswordStrengthText(customForm.strongPassword) }}</span>
              </div>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleCustomSubmit">提交</a-button>
                <a-button @click="handleCustomReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <div class="result-display">
          <div class="result-label">自定义表单数据：</div>
          <div class="result-value">
            <pre>{{ JSON.stringify(customForm, null, 2) }}</pre>
          </div>
        </div>
      </div>
    </div>

    <div class="example-section">
      <h3 class="section-title">组件代码示例</h3>
      <p class="section-description">表单验证的使用方法</p>

      <a-collapse>
        <a-collapse-panel key="1" header="基础验证规则">
          <pre class="code-block"><code>&lt;template&gt;
  &lt;a-form ref="formRef" :model="form" :rules="rules" layout="vertical"&gt;
    &lt;a-form-item label="用户名" name="username"&gt;
      &lt;a-input v-model:value="form.username" placeholder="请输入用户名" /&gt;
    &lt;/a-form-item&gt;
    &lt;a-form-item label="邮箱" name="email"&gt;
      &lt;a-input v-model:value="form.email" placeholder="请输入邮箱" /&gt;
    &lt;/a-form-item&gt;
    &lt;a-form-item&gt;
      &lt;a-button type="primary" @click="handleSubmit"&gt;提交&lt;/a-button&gt;
    &lt;/a-form-item&gt;
  &lt;/a-form&gt;
&lt;/template&gt;

&lt;script setup&gt;
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}
&lt;/script&gt;</code></pre>
        </a-collapse-panel>

        <a-collapse-panel key="2" header="自定义验证函数">
          <pre class="code-block"><code>&lt;script setup&gt;
// 自定义验证函数
const validateIdCard = (rule, value) =&gt; {
  if (!value) {
    return Promise.reject('请输入身份证号')
  }
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!idCardReg.test(value)) {
    return Promise.reject('请输入正确的身份证号')
  }
  return Promise.resolve()
}

const rules = {
  idCard: [
    { validator: validateIdCard, trigger: 'blur' }
  ]
}
&lt;/script&gt;</code></pre>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { CheckCircleOutlined, ExclamationCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'

// 基础表单
const basicFormRef = ref<FormInstance>()
const basicForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  phone: '',
  age: undefined
})

const basicRules: Record<string, Rule[]> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string) => {
        if (value !== basicForm.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120之间', trigger: 'blur' }
  ]
}

// 自定义表单
const customFormRef = ref<FormInstance>()
const customForm = reactive({
  idCard: '',
  bankCard: '',
  website: '',
  ipAddress: '',
  strongPassword: ''
})

// 自定义验证函数
const validateIdCard = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入身份证号')
  }
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!idCardReg.test(value)) {
    return Promise.reject('请输入正确的身份证号')
  }
  return Promise.resolve()
}

const validateBankCard = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入银行卡号')
  }
  if (!/^\d{16,19}$/.test(value)) {
    return Promise.reject('银行卡号应为16-19位数字')
  }
  return Promise.resolve()
}

const validateWebsite = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入网站地址')
  }
  const urlReg = /^https?:\/\/([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
  if (!urlReg.test(value)) {
    return Promise.reject('请输入正确的网站地址')
  }
  return Promise.resolve()
}

const validateIP = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入IP地址')
  }
  const ipReg = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  if (!ipReg.test(value)) {
    return Promise.reject('请输入正确的IP地址')
  }
  return Promise.resolve()
}

const validateStrongPassword = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入密码')
  }
  if (value.length < 8) {
    return Promise.reject('密码至少8个字符')
  }
  if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/.test(value)) {
    return Promise.reject('密码必须包含大小写字母、数字和特殊字符')
  }
  return Promise.resolve()
}

const customRules: Record<string, Rule[]> = {
  idCard: [{ validator: validateIdCard, trigger: 'blur' }],
  bankCard: [{ validator: validateBankCard, trigger: 'blur' }],
  website: [{ validator: validateWebsite, trigger: 'blur' }],
  ipAddress: [{ validator: validateIP, trigger: 'blur' }],
  strongPassword: [{ validator: validateStrongPassword, trigger: 'blur' }]
}

// 密码强度检测
const getPasswordStrength = (password: string) => {
  let strength = 0
  if (password.length >= 8) strength++
  if (/[a-z]/.test(password)) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/\d/.test(password)) strength++
  if (/[@$!%*?&]/.test(password)) strength++
  return strength
}

const getPasswordStrengthClass = (password: string) => {
  const strength = getPasswordStrength(password)
  if (strength <= 1) return 'weak'
  if (strength <= 3) return 'medium'
  return 'strong'
}

const getPasswordStrengthWidth = (password: string) => {
  const strength = getPasswordStrength(password)
  return `${(strength / 5) * 100}%`
}

const getPasswordStrengthText = (password: string) => {
  const strength = getPasswordStrength(password)
  if (strength <= 1) return '弱'
  if (strength <= 3) return '中等'
  return '强'
}

// 表单提交处理
const handleBasicSubmit = () => {
  basicFormRef.value?.validate().then(() => {
    message.success('基础表单验证通过！')
    console.log('基础表单数据:', basicForm)
  }).catch(() => {
    message.error('表单验证失败，请检查输入')
  })
}

const handleBasicReset = () => {
  basicFormRef.value?.resetFields()
}

const handleBasicValidate = () => {
  basicFormRef.value?.validate().then(() => {
    message.success('表单验证通过！')
  }).catch(() => {
    message.error('表单验证失败')
  })
}

const handleCustomSubmit = () => {
  customFormRef.value?.validate().then(() => {
    message.success('自定义表单验证通过！')
    console.log('自定义表单数据:', customForm)
  }).catch(() => {
    message.error('表单验证失败，请检查输入')
  })
}

const handleCustomReset = () => {
  customFormRef.value?.resetFields()
}
</script>

<style scoped>
.form-validation-demo {
  max-width: 1200px;
  margin: 0 auto;
}

.example-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.example-section:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 8px 0;
}

.section-description {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0 0 24px 0;
  line-height: 1.6;
}

.demo-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.demo-wrapper {
  padding: 24px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.demo-wrapper:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.demo-form {
  max-width: 100%;
}

.result-display {
  padding: 16px;
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.result-label {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  min-width: 100px;
}

.result-value {
  flex: 1;
  font-size: 12px;
  color: #595959;
}

.result-value pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  background: none;
  border: none;
  padding: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: #ff4d4f;
}

.strength-fill.medium {
  background: #faad14;
}

.strength-fill.strong {
  background: #52c41a;
}

.strength-text {
  font-size: 12px;
  color: #8c8c8c;
  min-width: 20px;
}

/* 代码示例 */
.code-block {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.45;
  overflow-x: auto;
  margin: 0;
}

.code-block code {
  background: none;
  padding: 0;
  font-size: inherit;
  color: #24292e;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .example-section {
    padding: 20px;
    margin-bottom: 16px;
  }

  .section-title {
    font-size: 18px;
  }

  .demo-container {
    gap: 16px;
  }

  .demo-wrapper {
    padding: 20px;
  }

  .result-display {
    flex-direction: column;
    gap: 8px;
  }

  .result-label {
    min-width: auto;
  }

  .password-strength {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
}
</style>